/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.odg.m_ui.tmp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.opu.odg.dg.TemplateRepository;
import org.opu.odg.dg.logicbeans.Template;

/**
 *
 * @author yura
 */
public class TemplateRepositoryImpl implements TemplateRepository {

    private File repositoryFolder;
    private File templateNamesFile;
    private Properties templateNames;

    public TemplateRepositoryImpl(File repositoryFolder, File templateNamesFile)
            throws IOException {
        this.repositoryFolder = repositoryFolder;
        this.templateNamesFile = templateNamesFile;
        this.templateNames = new Properties();

        FileUtils.touch(templateNamesFile);

        FileInputStream stream = new FileInputStream(templateNamesFile);
        try {
            this.templateNames.load(stream);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    @Override
    public Template get(int id) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(new File(repositoryFolder, "" + id));
            return new Template(id, IOUtils.toByteArray(stream));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    @Override
    public void saveOrUpdate(Template t) {
        if (t.getId() == null) {
            t.setId((int) (System.currentTimeMillis() / 1000));
        }
        FileOutputStream stream = null;
        Integer id = t.getId();
        try {
            stream = new FileOutputStream(new File(repositoryFolder, "" + id));
            IOUtils.write(t.getTemplateBinaryData(), stream);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    public List<TemplateBean> getList() {
        List<TemplateBean> list = new ArrayList<TemplateBean>();
        for(String id : repositoryFolder.list()){
            if (!templateNamesFile.getName().equals(id)) {
                int parseInt = Integer.parseInt(id);
                list.add(new TemplateBean(parseInt, getTemplateName(parseInt)));
            }
        }
        return list;
    }

    public void saveOrUpdate(Template t, String name) {
        saveOrUpdate(t);
        templateNames.setProperty("" + t.getId(), name);
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(templateNamesFile);
            templateNames.store(fout, "");
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(fout);
        }
    }

    public void remove(TemplateBean templateBean) throws IOException {
        Integer id = templateBean.getId();
        if (id != null) {
            String name = "" + id;
            new File(repositoryFolder, name).delete();
            templateNames.remove(name);
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(templateNamesFile);
                templateNames.store(fout, "");
            } finally {
                IOUtils.closeQuietly(fout);
            }
        }
    }

    private String getTemplateName(int id) {
        return templateNames.getProperty("" + id, "" + id);
    }

    public File getRepositoryFolder() {
        return repositoryFolder;
    }

    public static class TemplateBean implements Serializable{
        private Integer id;
        private String name;

        public TemplateBean(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return String.valueOf(name);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final TemplateBean other = (TemplateBean) obj;
            if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
                return false;
            }
            if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
                return false;
            }
            return true;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 17 * hash + (this.id != null ? this.id.hashCode() : 0);
            hash = 17 * hash + (this.name != null ? this.name.hashCode() : 0);
            return hash;
        }
    }

}
